const dgram = require("dgram");

module.exports = class UdpClient {

  obj = null
  link = {}

  onUpdate = () => { }

  static getInstant(){
    if (!this.obj) {
      this.obj = new UdpClient()
    }
    return this.obj
  }

  init() {
    let server = dgram.createSocket("udp4");
    server.bind(41234);

    server.on("error", function (err) {
      console.log("server error:n" + err.stack);
      server.close();
    });
    
    server.on("message", (msg, rinfo) =>{
      let data = msg.toString()
      if (data.length > 4 && data.substring(0, 4) == 'alin') {
        let arr = data.split("|")
        let hostname = arr[1]
        let ip = arr[2]
        let time = new Date().getTime()
        console.log(data)
        if (this.link[ip]) {
          this.link[ip].time = time
        } else {
          this.link[ip] = {
            name: hostname, ip, time
          }
          
        }
        this.onUpdate(this.link)
      }
    });
    server.on("listening", function () {
    });
    this.checkLink()
  }


  checkLink() {
    setInterval(()=>{
      let time = new Date().getTime()
      for (const key in this.link) {
        let v = this.link[key]
        if (time - v.time > 30*1000) {
          delete this.link[key]
          console.log("unload", key)
          this.onUpdate(this.link)
        }
      }
    }, 2000)

  }
}